package com.wanhelibs;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.logger.Logger;
import com.wanhe.base.BaseApplication;
import com.wanhe.base.model.base.Dish;
import com.wanhe.base.model.disgn.ViewItem;
import com.wanhe.base.util.AppManager;
import com.wanhe.base.util.ObjectUtil;
import com.wanhe.base.util.SystemUtil;
import com.wanhe.base.util.ViewUtil;
import com.wanhe.base.websocket.WebSocketTool;
import com.wanhe.base.websocket.callback.CartStateCallBack;
import com.wanhe.base.websocket.callback.ShopCartCallBack;
import com.wanhe.base.websocket.model.BillDish;
import com.wanhe.mealbookmodule.fragment.MealBookFragment;
import com.wanhe.shoppingcart.CartPop;
import com.wanhe.shoppingcart.bean.BillDishResponse;
import com.wanhe.shoppingcart.bean.CartChangeResponse;
import com.wanhe.shoppingcart.bean.CartStateDish;
import com.wanhe.shoppingcart.bean.CartStateResponse;
import com.wanhe.shoppingcart.manager.CartManager;
import com.wanhe.viewconf.ViewCreator;
import com.wanhe.viewconf.ViewOptions;
import com.wanhe.viewconf.views.child.BaseXYView;
import com.wanhe.viewconf.views.child.MealBookChildItemView;
import com.wanhelibs.adapter.IndicatorAdapter;
import com.wanhelibs.custom_view.views.AddSetMealDialog;
import com.wanhelibs.custom_view.views.ReduceSetMealDialog;
import com.wanhelibs.custom_view.views.TagSelectDialog;
import com.wanhelibs.indicator.CustomTab;
import com.wanhelibs.indicator.TabIndicatorLayout;

import java.lang.reflect.Type;
import java.util.List;

public class MealBookActivity extends AppCompatActivity {

	public static final String TAG = "MealBookActivity";

	private LinearLayout		tv_cart;
	private TabIndicatorLayout	indicatorLayout;
	private IndicatorAdapter	indicatorAdapter;
	private MealBookFragment	mealBookFragment;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SystemUtil.fullScreen(this);
		setContentView(R.layout.activity_meal_book);

		AppManager.getAppManager().finishAllActivity();
		ViewCreator.getInstance().setOptions(
				ViewOptions.builder().setCounterViewClickListener(counterViewClickListener)
						.setViewNormalClickListener(normalClickListener).build());

		/**
		 *
		 * @author 陈德基
		 * @time 2017/8/1 18:49
		 */
		indicatorLayout = (TabIndicatorLayout) findViewById(R.id.indicator);
		indicatorAdapter = new IndicatorAdapter(this);
		indicatorLayout.setAdapter(indicatorAdapter);

		/**
		 * 将菜单页面的碎片加入到activity中
		 *
		 * @author 陈德基
		 * @time 2017/7/12 15:28
		 */
		mealBookFragment = new MealBookFragment();
		mealBookFragment.setPageChangedListener(new MealBookFragment.OnPageChangedListener() {
			@Override
			public void onPageSelected(int position, int tid) {
				int typePosition = indicatorAdapter.getTypePosition(tid);
				indicatorLayout.setCurrentItem(typePosition);
			}
		});

		indicatorLayout.setTabItemClickListener(new TabIndicatorLayout.OnTabItemClickListener() {
			@Override
			public void onTabClick(View view, int index) {
				CustomTab tab = (CustomTab) view;
				int tid = tab.getmTypeID();
				mealBookFragment.jumpToType(tid);
			}
		});

		mealBookFragment.setTypeListAdapter(indicatorAdapter);
		getSupportFragmentManager().beginTransaction()
				.add(R.id.fl_fragment_holder, mealBookFragment).show(mealBookFragment).commit();

		tv_cart = (LinearLayout) findViewById(R.id.ll_cart_layout);
		tv_cart.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				int count = CartManager.getInstance().getCount();
				if (count <= 0) {
					Toast.makeText(getApplicationContext(), "亲，你还未点菜哦", Toast.LENGTH_SHORT).show();
					return;
				}
				int width = ViewUtil.getScreenWidth(MealBookActivity.this);
				int height = ViewUtil.getScreenHeight(MealBookActivity.this);
				CartPop cartPopupWindow = new CartPop(MealBookActivity.this, width, height - 500);
				cartPopupWindow.setShowLocationView(tv_cart);
				cartPopupWindow.showAtLocation(tv_cart, Gravity.TOP, 0, 0);
			}
		});

		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				initWebSocketCallBack();
			}
		}, 3000);

	}

	/**
	 * 初始化WebSocket相关的回调
	 */
	private void initWebSocketCallBack() {
		WebSocketTool.getInstance().setShopCartCallBack(new ShopCartCallBack() {
			@Override
			public void onCartChange(String body, int digest) {
				Log.d("onCartChange", "body=" + body + "===digest===" + digest);
				// 等于0表示是别人的操作，需要同步
				if (digest == 0) {
					if (body != null) {
						Gson gson = new Gson();
						CartChangeResponse cartChangeResponse = gson.fromJson(body,
								CartChangeResponse.class);
						if (cartChangeResponse.opType == 1 || cartChangeResponse.opType == 4) {
							Logger.i("====dishJson=====" + cartChangeResponse.dishJson);
							if (cartChangeResponse.dishJson != null
									&& cartChangeResponse.dishJson.length() > 1) {
								BillDish billDish = gson.fromJson(cartChangeResponse.dishJson,
										BillDish.class);
								String dishId = billDish.getDishID();
								if (dishId != null) {
									Logger.i("====getAmount=====" + billDish.getAmount());
									if (billDish.getAmount() > 0) {
										CartManager.getInstance().addItem(dishId,
												billDish.getAmount(), false);

									} else {
										CartManager.getInstance().reduceItem(dishId,
												Math.abs(billDish.getAmount()), false);
									}

								}
							}
						}
					}

				} else {
					// 自己的操作，目前暂时不处理
				}
			}
		});
		WebSocketTool.getInstance().setCartStateCallBack(new CartStateCallBack() {
			@Override
			public void onCartState(String body) {
				Logger.d("====onCartState====" + body);
				Gson gson = new Gson();
				CartStateResponse response = gson.fromJson(body, CartStateResponse.class);
				String orderCacheJson = response.orderCacheJson;
				Type type = new TypeToken <List <CartStateDish>>() {}.getType();
				List <CartStateDish> arrCartStateDishe = gson.fromJson(orderCacheJson, type);
				if (ObjectUtil.checkObjectList(arrCartStateDishe)) {
					for (int i = 0; i < arrCartStateDishe.size(); i++) {
						CartStateDish cartStateDish = arrCartStateDishe.get(i);
						List <BillDishResponse> arrBillDish = cartStateDish.Dishes;
						for (int j = 0; j < arrBillDish.size(); j++) {
							BillDishResponse billDish = arrBillDish.get(j);
							CartManager.getInstance().addItem(billDish);
						}
					}
				}
			}
		});
		WebSocketTool.getInstance().syncCartState();
	}

	private ViewOptions.OnCounterViewClickListener counterViewClickListener = new ViewOptions.OnCounterViewClickListener() {
		@Override
		public void plus(MealBookChildItemView view, Dish dish) {
			if (ObjectUtil.checkObject(dish)) {
				if (dish.isSetmeal()) {
					/**
					 * 显示套餐的详细选项框
					 *
					 * @author 陈德基
					 * @time 2017/8/4 14:34
					 */
					setmealDishOperation(dish);
				} else if (ObjectUtil.checkObjectList(dish.getDish_sizesList())
						|| ObjectUtil.checkObjectList(dish.getDish_tagsList())) {
					/**
					 * 显示带有口味信息的详细选项框
					 *
					 * @author 陈德基
					 * @time 2017/8/4 14:34
					 */
					specialDishOperation(dish);
				} else {
					normalDishOperation(view, dish);
				}
			}
		}

		@Override
		public void reduce(MealBookChildItemView view, Dish dish) {
			if (ObjectUtil.checkObject(dish)) {
				if (dish.isSetmeal()) {
					/**
					 * 显示套餐的详细选项框
					 *
					 * @author 陈德基
					 * @time 2017/8/4 14:34
					 */
					setmealReduceOperation(dish);
				} else if (ObjectUtil.checkObjectList(dish.getDish_sizesList())
						|| ObjectUtil.checkObjectList(dish.getDish_tagsList())) {
					/**
					 * 显示带有口味信息的详细选项框
					 *
					 * @author 陈德基
					 * @time 2017/8/4 14:34
					 */
					specialDishOperation(dish);
				} else {
					normalReduceOperation(view, dish);
				}
			}

		}
	};

	/**
	 * Methor Name:specialDishOperation<br/>
	 * Package Name:com.wanhelibs<br/>
	 * Date:2017/8/8 13:57<br/>
	 * author:chendeji<br/>
	 * desc: 普通的菜品数据中，如果有特殊的口味或者规格尺寸的数据的操作<br/>
	 * Copyright (c) 2017/8/8, 781571323@qq.com All Rights Reserved.
	 *
	 * @param dish
	 * @return
	 */
	private void specialDishOperation(Dish dish) {
		TagSelectDialog tagSelectDialog = TagSelectDialog.newInstance();
		tagSelectDialog.setDish(dish);
		tagSelectDialog.show(getSupportFragmentManager(), "TagSelectDialog");

	}

	/**
	 * Methor Name:setmealDishOperation<br/>
	 * Package Name:com.wanhelibs<br/>
	 * Date:2017/8/4 14:42<br/>
	 * author:chendeji<br/>
	 * desc: 套餐显示的弹窗显示<br/>
	 * Copyright (c) 2017/8/4, 781571323@qq.com All Rights Reserved.
	 *
	 * @param dish
	 * @return
	 */
	private void setmealDishOperation(Dish dish) {
		AddSetMealDialog addSetMealDialog = AddSetMealDialog.newInstance();
		addSetMealDialog.setDish(dish);
		addSetMealDialog.show(getSupportFragmentManager(), "AddSetMealDialog");
	}

	/**
	 * Methor Name:normalDishOperation<br/>
	 * Package Name:com.wanhelibs<br/>
	 * Date:2017/8/4 14:31<br/>
	 * author:chendeji<br/>
	 * desc: 普通菜的购物车添加处理<br/>
	 * Copyright (c) 2017/8/4, 781571323@qq.com All Rights Reserved.
	 *
	 * @param
	 * @return
	 */
	private void normalDishOperation(MealBookChildItemView view, Dish dish) {
		ViewItem.CountRule rule = view.getItem().getCustom();
		if (ObjectUtil.checkObject(rule)) {
			dish.setCountRule(rule);
			int itemCount = CartManager.getInstance().getSameGuidItemCount(dish.getDish_guid());
			if (itemCount == 0) {
				/**
				 * 第一次添加
				 *
				 * @author 陈德基
				 * @time 2017/7/27 17:59
				 */
				CartManager.getInstance().addItem(dish.getDish_guid(),
						rule.getMin() == 0 ? rule.getStep() : rule.getMin());
			} else if (itemCount >= rule.getMin() && itemCount < rule.getMax()) {
				/**
				 * 添加需要按照每次加多少数量进行添加
				 *
				 * @author 陈德基
				 * @time 2017/7/27 18:00
				 */
				CartManager.getInstance().addItem(dish.getDish_guid(), rule.getStep());
			} else if (itemCount >= rule.getMax()) {
				/**
				 * 到达最高数量了，不能再加了，进行提示
				 *
				 * @author 陈德基
				 * @time 2017/7/27 18:01
				 */
				Toast.makeText(BaseApplication.getApplicationComponent().getContext(),
						String.format("这道菜只能点%d份，点点其他菜吧~", rule.getMax()), Toast.LENGTH_SHORT)
						.show();
			}
		} else {
			CartManager.getInstance().addItem(dish.getDish_guid(), 1);
		}
	}


	private void normalReduceOperation(MealBookChildItemView view, Dish dish) {
		if (ObjectUtil.checkObject(dish)) {
			ViewItem.CountRule rule = view.getItem().getCustom();
			if (ObjectUtil.checkObject(rule)) {

				int itemCount = CartManager.getInstance().getSameGuidItemCount(dish.getDish_guid());
				if (itemCount > rule.getMin()) {
					CartManager.getInstance().reduceItem(dish.getDish_guid(), rule.getStep());
				} else if (itemCount <= rule.getMax()) {
					CartManager.getInstance().deleteItem(dish.getDish_guid());
				}

			} else {
				CartManager.getInstance().reduceItem(dish.getDish_guid(), 1);
			}
		}
	}

	private void setmealReduceOperation(Dish dish) {
		ReduceSetMealDialog reduceSetMealDialog = ReduceSetMealDialog.newInstance();
		reduceSetMealDialog.setDish(dish);
		reduceSetMealDialog.show(getSupportFragmentManager(), "ReduceSetMealDialog");
	}




	private ViewOptions.OnViewNormalClickListener normalClickListener = new ViewOptions.OnViewNormalClickListener() {
		@Override
		public void cartChangeReceiveXY(BaseXYView view, int x, int y) {
			Logger.t(TAG).i("购物车操作成功，返回控件信息，X坐标：%d ------- Y坐标：%d", x, y);
		}

		@Override
		public void operationView(BaseXYView view, int opType) {
			Logger.t(TAG).i("控件的事件操作类型为：" + (opType == CLICK ? "单击" : "长按"));
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			goback();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private boolean	isBackClicked;
	private long	mLastClickBackButtonTime;

	private void goback() {
		long currentTime = System.currentTimeMillis();
		long detal = currentTime - mLastClickBackButtonTime;
		if (isBackClicked && detal < 1300) {
			SystemUtil.exit(this, new SystemUtil.OnAppExit() {
				@Override
				public void exit() {
					// AppContext.getInstance().onTerminate();
				}
			});
		} else {
			isBackClicked = true;
			mLastClickBackButtonTime = currentTime;
			ViewUtil.ShortToast(BaseApplication.context,
					getResources().getString(R.string.home_tips_exit));
			// ToastUtil.showToast(AppContext.getInstance(),
			// getResources().getString(R.string.home_tips_exit));
		}
	}
}
